package cn.bgs.serviceedu.service.impl;

import cn.bgs.serviceedu.entity.Customer;
import cn.bgs.serviceedu.entity.Doctor;
import cn.bgs.serviceedu.dao.DoctorMapper;
import cn.bgs.serviceedu.service.DoctorService;
import cn.bgs.serviceedu.vo.RedisList;
import cn.bgs.serviceutils.utils.CSException;
import cn.bgs.serviceutils.utils.JwtUtils;
import cn.bgs.serviceutils.utils.RedisUtils;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 医生表 服务实现类
 * </p>
 *
 * @author YiChen
 * @since 2021-10-20
 */
@Service
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor> implements DoctorService {
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private DoctorMapper doctorMapper;

    @Override
    public List<RedisList> getRedisList() {
        //查询所有医生
        Set<String> key = redisUtils.scan("doctor");
        Iterator<String> iterator = key.iterator();
        //创建集合存入 id 和 val
        ArrayList<RedisList> redisLists = new ArrayList<>();
        while (iterator.hasNext()){
            String next = iterator.next();
            String[] split = next.split(":");
            String doctorId =split[1];
            int val = (int) redisUtils.get(next);
            RedisList redisList = new RedisList(doctorId,val);
            redisLists.add(redisList);
        }
        return redisLists;
    }

    @Override
    public List<Doctor> getListTop() {
        return doctorMapper.getListTop();
    }

    @Override
    public String login(Doctor doctor) {

        Doctor one = lambdaQuery().eq(Doctor::getDoctorCode,doctor.getDoctorCode()).one();

        if (one == null){
            throw new CSException(20001,"账号不存在");
        }
        MD5 md5 = new MD5();
        String s = md5.digestHex(doctor.getPassWord());
        if (!s.equals(one.getPassWord())){
            throw new CSException(20001,"密码错误");
        }
        return JwtUtils.getJwtToken(one.getDoctorId(),one.getDoctorName());
    }

    @Override
    public List<Doctor> listDoc(QueryWrapper<Doctor> wrapper) {
        return doctorMapper.listDoc(wrapper);
    }

    @Override
    public List<Doctor> findDoct(Integer customerId) {
        return doctorMapper.findDoct(customerId);
    }
}
